import mongoose from "mongoose";
export default class APIFeatures {
    public check
    public queryParams
    // Model, req.query
    constructor(check: mongoose.Query<any, any>, queryParams: Record<string, any>) {
        this.check = check;
        this.queryParams = queryParams;
    }

    // 1) Advanced filter
    filter() {
        let queryObj: Record<string, any> = { ...this.queryParams };
        let exxcludes = ['page', 'sort', 'limit', 'fields'];
        // 将上述参数排除
        exxcludes.forEach((el) => delete queryObj[el]);
        // 替换特殊符号：gte, gt, lte, lt
        let queryStr = JSON.stringify(queryObj);
        queryStr = queryStr.replaceAll(/\b(gte)|(gt)|(lte)|(lt)\b/g, ($1) => {
            return '$' + $1;
        });
        queryStr = JSON.parse(queryStr);
        // 查询
        this.check.find(queryStr as any)
        return this
    }

    // 2) Sorting
    sort() {
        let sortStr = this.queryParams.sort;
        if (sortStr) {
            sortStr = sortStr.replaceAll(',', ' ');
            this.check.sort(sortStr);
        } else {
            // 没有排序，使用 创建时间 来排序
            this.check.sort('-createdAt');
        }
        return this
    }

    // 3) Specify fields
    limitFields() {
        let fieldsStr = this.queryParams.fields;
        if (fieldsStr) {
            fieldsStr = fieldsStr.replaceAll(',', ' ');
            this.check.select(fieldsStr);
        } else {
            // _v mongodbs实际内部使用了他们，虽然可以禁掉，但这不是一个好习惯
            this.check.select('-__v');
        }
        return this
    }

    // 4) Pagination
    paginate() {
        const page = this.queryParams.page * 1 || 1;
        const limit = this.queryParams.limit * 1 || 100;
        const skip = (page - 1) * limit;
        this.check.skip(skip).limit(limit)
        return this
    }
}
